const express = require('express');
// const { setEncode, contrast } = require('../util/encode')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const User = require('../model/User')
const Comment = require('../model/Comment')
const Interview = require('../model/Interview')
const { secret } = require('../config/key')
const router = express.Router()

//注册：/user/register
router.post('/register', async (req, res) => {
    // 查询用户名是否存在，如果存在不允许注册
    const user = await User.findOne({username: req.body.username})
    if(user){
        return res.send({
            status: 409,
            msg: '该用户已存在！'
        })
    }
    // 对密码进行加密处理
    // req.body.password = setEncode(req.body.password)
    // 如果注册用户不存在，则将注册信息保存到数据库中
    const newUser = await new User(req.body).save()
    res.send({
        status: 200,
        msg: '注册成功！'
    })
})

//登录： /user/login
router.post('/login', async (req, res) => {
    const Count = await Interview.find()
    const a = parseInt(Count[Count.length-1].count)
    console.log(Count[Count.length - 1]._id);
    //5f7c6e5dbcfc762188229b1c
    const b = await Interview.update({_id: '5f7c6e5dbcfc762188229b1c'},{$set:{count: parseInt(a + 1)}})
    // const newUser = await new Interview({count:1}).save()
    const list = await User.find()
    // 1.查询用户是否存在
    const user = await User.findOne({username: req.body.username})
    if(!user){
        return res.send({
            status: 400,
            msg: '帐号或密码错误'
        })
    }
    // else {
    //     // 2.如果用户存在，判断密码
    //     if (req.body.password !== user.password) {
    //         return res.status(422).send('密码错误')
    //     }else {
    //         res.send('token')
    //     }
    // }

    // 对密码进行解密处理对比，返回一个布尔值
    // let isPassword = contrast(req.body.password, user.password, salt)

    //如果登录用户存在，则校验密码是否正确
    let  isPassword = (req.body.password == user.password)
    if (!isPassword) {
        return res.send({
            status: 400,
            msg: '帐号或密码错误'
        })
    }
    // res.send(user)
    // 登录成功返回token
    // const token = user._id + '.' + req.body.username
    const { _id, username, name, idiograph, picture, articleThumbs } = user
    //参数一是传值规则,参数二是加密规则,参数三是定义token的存在时间
    const token ="Bearer " + jwt.sign({_id,username},secret,{expiresIn:'24h'})
    res.send({
        _id,
        status: 200,
        token: token,
        username,
        name,
        picture,
        idiograph,
        articleThumbs,
        lenght: list.length,
        count: a+1
    })
})

//修改个人资料： /user/edit
router.put('/edit', async (req, res) => {
    if (!req.body.username){
        return res.send({
            status: 401,
            msg: '修改资料失败！'
        })
    }
    else {
        const commentUser =  await Comment.find({username: req.body.username})
        commentUser.forEach(async item => {
            await Comment.update({_id: item._id},{$set:{name:req.body.name}})
        })
        const user = await User.update({username: req.body.username},{$set:{name:req.body.name,idiograph:req.body.idiograph}})
        if(!user){
            return res.send({
                status: 401,
                msg: '修改资料失败！'
            })
        } else {
            res.send({
                status: 200,
                msg: '修改资料成功！'
            })
        }
    }
})
//修改头像
router.put('/picture', async (req, res) => {
    if (!req.body.username){
        return res.send({
            status: 401,
            msg: '修改资料失败！'
        })
    }
    else {
        const commentUser =  await Comment.find({username: req.body.username})
        commentUser.forEach(async item => {
           await Comment.update({_id: item._id},{$set:{picture:req.body.picture}})
        })
        console.log(commentUser);
        const user = await User.update({username: req.body.username},{$set:{picture:req.body.picture}})
        if(!user){
            return res.send({
                status: 401,
                msg: '修改资料失败！'
            })
        } else {
            res.send({
                status: 200,
                msg: '修改头像成功！'
            })
        }
    }
})

// 获取用户列表
router.get('/getuserNumber', async(req, res) => {
    const list = await User.find()
    res.send(list.length)
})

//条件查询用户
router.get('/getOneUserMessage', async(req, res) => {
    const user = await User.findOne({username: req.param("username")})
    res.send({
        name: user.name,
        idiograph: user.idiograph,
        picture: user.picture
    })
})



// 验证
router.get('/verify', async (req,res) => {
    console.log(req.headers.authorization)
    // // 1.获取token
    // const token = req.headers.authorization.split(' ')[1]
    // const id = token.split('.')[0]
    // const username = token.split('.')[1]
    // console.log(id,username)
    // // 2.查询用户是否存在
    // const user = User.findById(id)
    // if (!user){
    //     return res.status(422).send('用户错误')
    // }
    // // 3查看username
    // if(username !== user.username) {
    //     res.status(422).send('用户错误')
    // }else {
    //     if (user.isAdmin === '0') {
    //         res.status(409).send('没有权限')
    //     }else if(user.isAdmin == 1) {
    //         res.send('Admin')
    //     }
    // }
    const token = req.headers.authorization.split(' ').pop()
    console.log(jwt.verify(token,secret))
    const { _id } = jwt.verify(token,secret)
    console.log(_id)
} )



module.exports = router
